<template>
  <div style="height: 100%;">
    <el-row :gutter="20" style="margin-left:0px;margin-right:0px;height: 100%;">
      <el-col :span="6" style="padding:0px;  height: 100%; border-right: 1px solid#ccc;">
        <!-- 组织机构树 -->
        <div class="zztree">
          <div slot="header" class="clearfix zztree-title">
            <span class="span-title">用户管理</span>
          </div>
          <div class="zztree-con tree-detail" style="height: 100%;overflow-y: auto;">
            <el-tree ref='treeRef'
                     :data="treeData"
                     :props="defaultProps"
                     @node-click="handleNodeClick"
                     :expand-on-click-node='false'
                     node-key="id"
                     :highlight-current='true'
                     :default-expand-all='true'>
                        <span class="custom-tree-node" slot-scope="{ node, data }">
                          <span v-if="data.other.Status == 0" class="ztrrName" style="display: inline-block;" :title="data.name">{{ data.name }}</span>
                          <span v-if="data.other.Status == 1" class="ztrrName" style="display: inline-block;color:red" :title="data.name">{{ data.name }}(禁用)</span>
                        </span>
                     </el-tree>
          </div>
        </div>
      </el-col>
      <el-col :span="18" style="padding:0px;height: 100%;overflow-y: auto;">
        <div class="job-tab">
          <div slot="header" class="clearfix zztree-title">
            <span class="span-title">用户列表</span>
          </div>
          <div style="margin-top:15px;">
            <div class="select-container">
              <el-row class="">
                <el-col :span="24" class="">
                  <el-form ref="form" label-width="100px" label-position='right' size="small" :inline="true">
                    <el-col :span="4" >
                      <el-form-item label="" style="margin:12px 5px;">
                        <el-input placeholder="登录名称" prefix-icon="el-icon-search" v-model="listQuery.condition.loginName.value" clearable>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="4" >
                      <el-form-item label="" style="margin:12px 3px;">
                        <el-input placeholder="用户名称" prefix-icon="el-icon-search" v-model="listQuery.condition.name.value" clearable>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <!--  -->
                      <el-form-item label="" style="margin:12px 0px;">
                        <el-select placeholder="请选择用户状态"  v-model="listQuery.condition.status.value" clearable>
                          <el-option v-for="(item, index) in statusOptionsData" :key="index" :label="item.display_name" :value="item.key">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="10" style="padding-left:10px;margin-top:12px;float:right;margin-right:0">
                      <el-button size="small" style="height:30px;padding-top:0px;line-height:30px;" type="success" icon="el-icon-edit" @click="getList(selectOuinfoId,'find')">查 询</el-button>
                      <el-button size="small" style="height:30px;padding-top:0px;line-height:30px;" type="danger" icon="el-icon-circle-close-outline" @click="handleReset">重 置</el-button>
                      <el-button size="small" style="height:30px;padding-top:0px;line-height:30px;" type="primary" icon="el-icon-circle-plus-outline" @click="handleCreate">新建</el-button>
                    </el-col>
                  </el-form>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
        <div class="job-table">
          <el-table :key='tableKey' :data="list"
                    v-loading="listLoading"
                    element-loading-text="给我一点时间"
                    height="320"
                    size="small"
                    border fit highlight-current-row style="width: 100%;border:#eeeeee">
            <el-table-column align="center" label="序号" type="index">
              <template slot-scope="scope">
              <span>{{scope.$index + (serialNumber - 1) * listQuery.rowBounds.limit + 1}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="登录名" width="120" prop="loginName">
              <template slot-scope="scope">
                <span>{{scope.row.loginName}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="用户名" width="120" prop="name">
              <template slot-scope="scope">
                <span>{{scope.row.name}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="机构名称" width="200" prop="orgName">
              <template slot-scope="scope">
                <span>{{scope.row.orgName}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="状态" prop="status">
              <template slot-scope="scope">
                <span>{{scope.row.status | statusFilter}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="允许访问开始/结束时间" width="180" prop="accessStartDate">
              <template slot-scope="scope">
                <span>{{scope.row.accessStartDate}}</span>&#10;<span>{{scope.row.accessEndDate}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="职务" prop="postStatus">
              <template slot-scope="scope">
                <span>{{jobfilter(scope.row.postStatus)}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操 作" width="380px">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleEdit(scope.row)" style="width:30px; margin-left:5px;">编辑</el-button>
                <el-button type="text" size="small" @click="handleDelete(scope.row,'delete')" v-if="scope.row.status != '2'" style="width:30px; margin-left:5px;">删除</el-button>
                <!--<el-button type="text" size="small" @click="updateIm(scope.row)" style="width:30px; margin-left:5px;">同步</el-button>-->
                <el-button type="text" size="small" @click="handleRestPassword(scope.row)" v-if="scope.row.status != '2'" style="width:50px; margin-left:5px;">重置密码</el-button>
                <el-button type="text" size="small" @click="handleUserRole(scope.row)" v-if="scope.row.status != '2'" style="width:50px; margin-left:5px;">配置角色</el-button>
                <el-button type="text" size="small" @click="handleUserPri(scope.row)" v-if="scope.row.status != '2'" style="width:60px; margin-left:1px;">查看权限</el-button>
                <el-button type="text" size="small" @click="handleUserSec(scope.row)" v-if="scope.row.status != '2'" style="width:60px; margin-left:1px;">秘书设置</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination background
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :current-page="listQuery.page"
                           :page-sizes="[10,20,30, 50]"
                           :page-size="listQuery.rowBounds.limit"
                           layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>
    <!--新增弹出层-->
    <el-dialog
      custom-class="addUserDialog"
      v-if="dialogVisibleAddUser"
      :close-on-click-modal="false"
      title="新增"
      :visible.sync="dialogVisibleAddUser"
      width="70%">
      <newUser :addUserData="addUserData" @changeCloseDialog="changeCloseDialog"></newUser>
    </el-dialog>
    <!--编辑弹出层-->
    <el-dialog
      custom-class="editUserDialog"
      v-if="dialogVisibleEditUser"
      :close-on-click-modal="false"
      title="编辑"
      :visible.sync="dialogVisibleEditUser"
      width="70%">
      <editUser :editUserData="editUserData" @changeCloseDialog="changeCloseDialog"></editUser>
    </el-dialog>
    <!--编辑角色弹出层-->
    <el-dialog
      v-if="dialogVisibleEditUserRole"
      :close-on-click-modal="false"
      title="配置角色"
      :visible.sync="dialogVisibleEditUserRole"
      width="70%">
      <editUserRole :editUserRoleData="editUserRoleData" @changeCloseDialog="changeCloseDialog"></editUserRole>
    </el-dialog>
    <!--查看权限弹出层-->
    <el-dialog
      v-if="dialogVisibleViewUserPri"
      :close-on-click-modal="false"
      title="查看权限"
      :visible.sync="dialogVisibleViewUserPri"
      width="40%">
      <viewPri :viewUserPriData="editUserRoleData" @changeCloseDialog="changeCloseDialog"></viewPri>
    </el-dialog>
    <!--添加秘书弹出层-->
    <el-dialog
      v-if="dialogVisibleViewUserSec"
      :close-on-click-modal="false"
      title="秘书设置"
      :visible.sync="dialogVisibleViewUserSec"
      width="60%">
      <editSecretaryUser :editSecretaryData="editUserRoleData" @changeCloseDialog="changeCloseDialog"></editSecretaryUser>
    </el-dialog>
  </div>
</template>

<script>
import { getOrgTree, compositeSelect, forceDeleteItem, updateItem } from '@/api/systemManage/userManagement'
// import { deleteImUser, updateImUser } from '@/api/systemManage/userManagement'
import {
  jobtitleKeyValue,
  statusOptionsData,
  joblevelKeyValue,
  statusKeyValue
} from '@/utils/allOptions'
import { mapGetters } from 'vuex'
import _ from 'lodash'
import newUser from './newUser'
import editUser from './editUser'
import editUserRole from '@/views/systemManage/commonComponents/userRole/editUserRole'
import viewPri from './viewPri'
import editSecretaryUser from './editSecretaryUser'
export default {
  components: {
    newUser,
    editUser,
    editUserRole,
    viewPri,
    editSecretaryUser
  },
  data() {
    return {
      postStatusOptions: [],
      dialogVisibleAddUser: false,
      dialogVisibleEditUser: false,
      dialogVisibleEditUserRole: false,
      dialogVisibleViewUserPri: false,
      dialogVisibleViewUserSec: false,
      addUserData: {
        addUserOrgId: '',
        addUserOrgName: ''
      },
      editUserData: [],
      editUserRoleData: {
        userId: '',
        userOrgId: ''
      },
      addName: '',
      listLoading: false,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      listQuery: {
        rowBounds: {
          offset: 0,
          limit: 10
        },
        orgId: '',
        condition: {
          pt: {
            property: 'pt',
            value: '0',
            type: 'EQ'
          },
          loginName: {
            property: 'loginName',
            value: '',
            type: 'LIKE'
          },
          name: {
            property: 'name',
            value: '',
            type: 'LIKE'
          },
          status: {
            property: 'status',
            value: '0',
            type: 'ENUM'
          }
        },
        sort: [{
          direction: 'ASC',
          property: 'orderNo'
        }]
      },
      list: [],
      tableKey: 0,
      total: null,
      statusOptionsData,
      selectOuinfoId: null,
      serialNumber: 1
    }
  },
  filters: {
    jobtitleFilter(target) {
      return jobtitleKeyValue[target]
    },
    joblevelFilter(target) {
      return joblevelKeyValue[target]
    },
    statusFilter(target) {
      return statusKeyValue[target]
    }
  },
  computed: {
    jobfilter() {
      return function(index) {
        if (index !== null) {
          for (const item of this.postStatusOptions) {
            if (item.codeKey == index) {
              return item.codeName
            }
          }
        }
      }
    }
  },
  methods: {
    GetCodeList() {
      let args = {}
      args.codeType = 'JOB_TYPE_CATEGORY_CODE'
      args.codeStatus = '0'

      this.$store.dispatch('SysCodeListByCodeType', args).then(res => {
        let data = res.data
        if (data && data.length > 0) {
          data.forEach((item, i) => {
            item.id = JSON.stringify({
              'id': item.codeKey,
              'name': item.codeName
            })
          })
        }
        this.postStatusOptions = data
        this.loading = false
      }).catch((err) => {
        console.log(err)
      })
    },
    changeCloseDialog() {
      this.dialogVisibleAddUser = false
      this.dialogVisibleEditUser = false
      this.dialogVisibleEditUserRole = false
      this.dialogVisibleViewUserPri = false
      this.dialogVisibleViewUserSec = false
      this.getList(this.selectOuinfoId)
    },
    handleRestPassword(row) {
      this.$confirm(
        '此操作将重置密码, 是否继续?',
        '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          var data = {
            condition: {
              id: {
                property: 'id',
                value: row.id,
                type: 'EQ'
              }
            },
            value: {
              password: '123456'
            }
          }
          updateItem(data).then(() => {
            this.$notify({
              title: '成功',
              message: '用户' + row.name + '密码重置成功',
              type: 'success',
              duration: 2000
            })
            this.getList(this.selectOuinfoId)
          })
        })
    },
    handleNodeClick(data, node) {
      // this.$store.state.user.selectOuinfoId = data.id
      this.$store.commit('SET_SELECTOUINFOID', data.id)
      this.$store.commit('SET_SELECTOUINFONAME', data.name)
      this.selectOuinfoId = data.id
      this.addName = data.name
      this.listQuery.rowBounds.offset = 0
      this.serialNumber = 1
      this.total = 0
      this.getList(data.id)
    },
    getTree() {
      const id = { id: this.$store.getters.orgId }
      getOrgTree(id).then(response => {
        this.treeData = response.data.data
        this.$nextTick(() => {
          this.$refs.treeRef.setCurrentKey(this.$store.state.user.selectOuinfoId) // treeBox 元素的ref   value 绑定的node-key
        })
        if (this.$store.state.user.selectOuinfoName) {
          this.addName = this.$store.state.user.selectOuinfoName
        } else {
          this.addName = this.treeData[0].name
        }
        if (this.$store.state.user.selectOuinfoId) {
          this.selectOuinfoId = this.$store.state.user.selectOuinfoId
        } else {
          this.selectOuinfoId = this.treeData[0].id
        }
        this.listQuery.condition.status.value = '活动'
        this.getList(this.selectOuinfoId, 'init')
      })
    },
    handleCreate() {
      if (this.selectOuinfoId) {
        this.addUserData.addUserOrgId = this.selectOuinfoId
        this.addUserData.addUserOrgName = this.addName
        this.dialogVisibleAddUser = true
        // this.$router.push({ name: 'newUser', params: { id: this.selectOuinfoId }})
      } else {
        this.$message({
          message: '请点击左侧选择组织机构。',
          type: 'warning'
        })
      }
    },
    handleIp() {
      this.$router.push({ name: 'editIp', params: { id: row.id }})
    },
    handleEdit(row) {
      this.editUserData.userId = row.id
      this.editUserData.orgId = row.orgId
      this.dialogVisibleEditUser = true
      // this.$router.push({ name: 'editUser', params: { id: row.id }})
    },
    // updateIm(row) {
    //   const imUserData = {
    //     'userId': row.loginName,
    //     'name': row.name,
    //     'mobile': row.mobilePhone,
    //     'phone': row.telephone,
    //     'email': row.email,
    //     'gender': Number(row.gender),
    //     'dept': [0]
    //   }
    //   updateImUser(imUserData).then(res => {
    //     if (res.data.statusCode === 200) {
    //       this.$notify({
    //         title: '成功',
    //         message: '同步IM成功',
    //         type: 'success',
    //         duration: 2000
    //       })
    //     } else {
    //       this.$notify({
    //         title: '错误',
    //         message: '同步IM失败',
    //         type: 'error',
    //         duration: 2000
    //       })
    //     }
    //   })
    // },
    handleUserRole(row) {
      this.editUserRoleData.userId = row.id
      this.editUserRoleData.userOrgId = row.orgId
      this.dialogVisibleEditUserRole = true
    },
    handleUserPri(row) {
      this.editUserRoleData.userId = row.id
      this.editUserRoleData.userOrgId = row.orgId
      this.dialogVisibleViewUserPri = true
    },
    handleUserSec(row) {
      this.editUserRoleData.userId = row.id
      this.editUserRoleData.userOrgId = row.orgId
      this.dialogVisibleViewUserSec = true
    },
    // 翻页器使用
    handleSizeChange(val) {
      this.listQuery.rowBounds.limit = val
      this.listQuery.rowBounds.offset = this.listQuery.rowBounds.limit * (this.serialNumber - 1)
      this.getList(this.selectOuinfoId)
    },
    // 翻页器使用
    handleCurrentChange(val) {
      this.serialNumber = val
      this.listQuery.rowBounds.offset =
        this.listQuery.rowBounds.limit * (val - 1)
      this.getList(this.selectOuinfoId)
    },
    getList(orgId, flag) {
      if (orgId) {
        // this.listQuery.condition.orgId.value = orgId
        this.listQuery.orgId = orgId
        if (flag === 'find') {
          this.listQuery.rowBounds.offset = 0
          this.serialNumber = 1
        }
        if (flag === 'delete') {
          if (this.listQuery.rowBounds.offset == (this.total - 1) &&
           this.listQuery.rowBounds.offset >= this.listQuery.rowBounds.limit) {
            this.listQuery.rowBounds.offset -= this.listQuery.rowBounds.limit
            if (this.serialNumber * this.listQuery.rowBounds.limit >= this.total) {
              this.serialNumber -= 1
            }
          }
        }
        let search = _.cloneDeep(this.listQuery)
        if (search.condition.status.value === '活动') {
          search.condition.status.value = [0]
        }
        compositeSelect(search).then(response => {
          this.list = response.data.data.records
          this.total = response.data.data.count
          this.listLoading = false
        })
      } else {
        this.$message({
          message: '请选择组织机构。',
          type: 'warning'
        })
      }
    },
    handleDelete(row, flag) {
      this.$confirm(
        '此操作将删除【' + row.name + '】, 是否继续?',
        '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          const data = {
            'id': row.id
          }
          forceDeleteItem(data).then(response => {
            this.$nextTick(() => {
              this.$refs.treeRef.setCurrentKey(this.$store.state.user.selectOuinfoId) // treeBox 元素的ref   value 绑定的node-key
            })
            // deleteImUser(data).then(res => {
            //   if (res.data.statusCode === 200) {
            //     this.$notify({
            //       title: '成功',
            //       message: '同步IM成功',
            //       type: 'success',
            //       duration: 2000
            //     })
            //   }
            // })
            this.$message({
              message: '【' + row.name + '】已经被删除。',
              type: 'success'
            })
            // this.handleReset()
            this.getList(this.selectOuinfoId, flag)
          })
        })
        .catch(error => {
          console.error(error)
        })
    },
    handleReset() {
      this.listQuery.condition.loginName.value = ''
      this.listQuery.condition.name.value = ''
      this.listQuery.condition.status.value = ''
      this.listQuery.rowBounds.offset = 0
      this.listQuery.rowBounds.limit = 10
      this.list = null
      this.total = 0
      this.serialNumber = 1
      this.getTree()
    }
  },
  created() {
    this.GetCodeList()
  },
  mounted() {
    this.getTree()
  }
}
</script>
<style>
  .addUserDialog .el-dialog__body{
    padding: 0 20px;
  }
  .editUserDialog .el-dialog__body{
    padding: 0 20px;
  }
</style>
<style scoped>
  .text {
    font-size: 14px;
  }
.select-container{
    padding: 10px 10px;
    margin-bottom: 10px;
    margin-left: 3px;
    margin-right: 3px;
    border-radius: 4px;
    border: 1px solid #eeeeee;
  }
  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both;
  }

  .box-card {
    width: 100%;
  }

  .el-button--mini,
  .el-button--mini.is-round {
    padding: 3px 5px;
  }
  .span-title{
    float: left;
    line-height: 16px;
    border-left:4px solid #000;
    padding-left: 10px;
    font-size: 16px;
    margin-top: 7px;
  }
</style>
